<template>
  <div class="usageRecord">
    <el-card shadow="hover" class="layout-padding-auto">
      <el-row class="row">
        <el-col :span="8">
          <div>备件编号：{{ detailForm.partNum }}</div>
        </el-col>
        <el-col :span="8">
          <div>备件名称：{{ detailForm.partName }}</div>
        </el-col>
        <el-col :span="8">
          <div>备件类型：{{ detailForm.partTypeName }}</div>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="出库记录" name="1">
          <TableSearch
            :search="state.search"
            @search="onSearch"
            @listenClick="listenClick"
          />
          <Table
            ref="tableRef"
            v-bind="state.tableData"
            class="table-demo"
            @delRow="onTableDelRow"
            @pageChange="onTablePageChange"
            @listenClick="listenClick"
            @dataList="dataList1"
          >
          </Table>
        </el-tab-pane>
        <el-tab-pane label="入库记录" name="2">
          <TableSearch
            :search="state.search2"
            @search="onSearch2"
            @listenClick="listenClick"
          />
          <Table
            ref="table2Ref"
            v-bind="state.tableData2"
            class="table-demo"
            @delRow="onTableDelRow2"
            @pageChange="onTablePageChange2"
            @listenClick="listenClick"
            @dataList="dataList2"
          >
          </Table>
        </el-tab-pane>
      </el-tabs>
      <InOutDetailDialog
        :inOutDialog="inOutDialog"
        :inOutForm="inOutForm"
        @closeDetail="closeDetail"
      >
      </InOutDetailDialog>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { ElMessage, TabsPaneContext } from 'element-plus'
import { ref, reactive, defineAsyncComponent, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { dictionaryList } from '/@/api/publicApi'
import {
  getOutInfoApi,
  getSpareInfoApi,
  singleDerivedRecordApi,
  singleDerivedRecordInApi
} from '/@/api/spare'
import { getButtonListByRoleApi } from '/@/api/publicApi'
import { Session } from '/@/utils/storage'
const menu = Session.get('menu')
const buttonCodes = ref<any>([])
const Table = defineAsyncComponent(
  () => import('/@/components/table/index.vue')
)
const TableSearch = defineAsyncComponent(
  () => import('/@/components/table/search.vue')
)
const InOutDetailDialog = defineAsyncComponent(
  () => import('./components/InOutDetailDialog.vue')
)
const route = useRoute()
const id = ref(JSON.parse(JSON.stringify(route.query.id)))
onMounted(() => {
  getdetailForm()
  menu.forEach(async (element: any) => {
    if (element.menuUrl == '/spare/spareList') {
      let res = await getButtonListByRoleApi({
        terminalType: 1,
        menuPid: element.id
      })
      res.data.forEach((item: any) => {
        buttonCodes.value.push(item.buttonCode)
      })
    }
  })
})
const detailForm = ref({
  partNum: '',
  partName: '',
  partTypeName: ''
})
const activeName = ref('1')
const retrievalTypes = ref<any>([])
const warehouseTypes = ref<any>([])
const getType = () => {
  dictionaryList({ configType: 'retrieval_type', keyword: '' }).then((res) => {
    if (res.code == 0) {
      state.search.param.forEach((i: any) => {
        if (i.prop == 'retrievalType') {
          i.options = res.data
          i.options.unshift({
            configValue: '全部',
            customizeFlag: 0,
            id: '',
            parentId: '0'
          })
        }
      })
    }
  })
  dictionaryList({ configType: 'warehouse_type', keyword: '' }).then((res) => {
    if (res.code == 0) {
      state.search2.param.forEach((i: any) => {
        if (i.prop == 'warehouseType') {
          i.options = res.data
          i.options.unshift({
            configValue: '全部',
            customizeFlag: 0,
            id: '',
            parentId: '0'
          })
        }
      })
    }
  })
}
getType()

// 定义变量内容
const tableRef = ref<RefType>()
const table2Ref = ref<RefType>()
const state = reactive<TableDemoState>({
  tableData: {
    flash: false, // 刷新表格
    // 表头内容（必传，注意格式）
    header: [
      { key: 'retrievalType', colWidth: '', title: '出库类型', type: 'text' },
      { key: 'totalAmount', colWidth: '', title: '操作数量', type: 'text' },
      { key: 'surplusAmount', colWidth: '', title: '操作后数量', type: 'text' },
      { key: 'startAmount', colWidth: '', title: '操作前数量', type: 'text' },
      { key: 'createUserName', colWidth: '', title: '操作人', type: 'text' },
      { key: 'createTime', colWidth: '', title: '操作时间', type: 'text' }
    ],
    columnBtn: [
      {
        name: 'Outdetails',
        text: '详情',
        type: 'primary',
        btns: buttonCodes.value,
        btnCode: 'partUsageRecordBtn'
      }
    ],
    // 配置项（必传）
    config: {
      listApi: '/device/mobile/devicePartRetrieval/singlePartPageList',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: true, // 是否显示表格序号
      isSelection: false, // 是否显示表格多选
      isOperate: true, // 是否显示表格操作栏
      isExtend: false // 是否可以扩展
    },
    // 搜索参数
    param: {
      partId: id.value // 必传参数，分页的不要传
    }
  },
  tableData2: {
    flash: false, // 刷新表格
    // 表头内容（必传，注意格式）
    header: [
      { key: 'warehouseType', colWidth: '', title: '入库类型', type: 'text' },
      { key: 'totalAmount', colWidth: '', title: '操作数量', type: 'text' },
      { key: 'startAmount', colWidth: '', title: '操作前数量', type: 'text' },
      { key: 'surplusAmount', colWidth: '', title: '操作后数量', type: 'text' },
      { key: 'createUserName', colWidth: '', title: '操作人', type: 'text' },
      { key: 'createTime', colWidth: '', title: '操作时间', type: 'text' }
    ],
    columnBtn: [
      {
        name: 'Indetails',
        text: '详情',
        type: 'primary',
        btns: buttonCodes.value,
        btnCode: 'partUsageRecordBtn'
      }
    ],
    // 配置项（必传）
    config: {
      listApi: '/device/mobile/devicePartWarehouse/singlePartPageList',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: true, // 是否显示表格序号
      isSelection: false, // 是否显示表格多选
      isOperate: true, // 是否显示表格操作栏
      isExtend: false // 是否可以扩展
    },
    // 搜索参数
    param: {
      partId: id.value // 必传参数，分页的不要传
    }
  },
  // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
  search: {
    param: [
      {
        label: '',
        prop: 'keyword',
        placeholder: '可输入操作人搜索',
        type: 'input'
      },
      {
        label: '时间筛选',
        prop: 'daterange',
        placeholder: '选择时间',
        type: 'daterange'
      },
      {
        label: '出库类型',
        prop: 'retrievalType',
        placeholder: '出库类型',
        options: [],
        type: 'select2'
      }
    ],
    btn: [
      {
        text: '导出记录',
        fun: 'exportRecordOut',
        disable: false,
        loading: false,
        type: 'primary',
        hide(): boolean {
          return false
        },
        btns: buttonCodes.value,
        btnCode: 'partUsageRecordBtn'
      }
    ],
    reset: true
  },
  // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
  search2: {
    param: [
      {
        label: '',
        prop: 'keyword',
        placeholder: '可输入操作人搜索',
        type: 'input'
      },
      {
        label: '时间筛选',
        prop: 'daterange',
        placeholder: '选择时间',
        type: 'daterange'
      },
      {
        label: '入库类型',
        prop: 'warehouseType',
        placeholder: '入库类型',
        options: [],
        type: 'select2'
      }
    ],
    btn: [
      {
        text: '导出记录',
        fun: 'exportRecordIn',
        disable: false,
        loading: false,
        type: 'primary',
        hide(): boolean {
          return false
        },
        btns: buttonCodes.value,
        btnCode: 'partUsageRecordBtn'
      }
    ],
    reset: true
  }
})

// 初始化列表数据
const getTableData = () => {
  state.tableData.flash = !state.tableData.flash
}

const list1 = ref([])
const dataList1 = (val: any) => {
  list1.value = val.records
}

// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
  state.tableData.param = Object.assign({}, state.tableData.param, { ...data })
  if (
    state.tableData.param.daterange &&
    state.tableData.param.daterange.length != 0
  ) {
    state.tableData.param.startTime = state.tableData.param.daterange[0]
    state.tableData.param.endTime = state.tableData.param.daterange[1]
  } else {
    state.tableData.param.startTime = ''
    state.tableData.param.endTime = ''
  }
  if (state.tableData.param.retrievalType == '全部') {
    state.tableData.param.retrievalType = ''
  }
  state.tableData.flash = !state.tableData.flash
}
// 删除当前项回调
const onTableDelRow = (row: EmptyObjectType) => {
  ElMessage.success(`删除${row.name}成功！`)
  getTableData()
}
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
  state.tableData.param.pageNum = page.pageNum
  state.tableData.param.pageSize = page.pageSize
  getTableData()
}
// 初始化列表数据
const getTableData2 = () => {
  state.tableData2.flash = !state.tableData2.flash
}

const list2 = ref([])
const dataList2 = (val: any) => {
  list2.value = val.records
}

// 搜索点击时表单回调
const onSearch2 = (data: EmptyObjectType) => {
  state.tableData2.param = Object.assign({}, state.tableData2.param, {
    ...data
  })
  if (
    state.tableData2.param.daterange &&
    state.tableData2.param.daterange.length != 0
  ) {
    state.tableData2.param.startTime = state.tableData2.param.daterange[0]
    state.tableData2.param.endTime = state.tableData2.param.daterange[1]
  } else {
    state.tableData2.param.startTime = ''
    state.tableData2.param.endTime = ''
  }
  if (state.tableData2.param.warehouseType == '全部') {
    state.tableData2.param.warehouseType = ''
  }
  state.tableData2.flash = !state.tableData2.flash
}
// 删除当前项回调
const onTableDelRow2 = (row: EmptyObjectType) => {
  ElMessage.success(`删除${row.name}成功！`)
  getTableData2()
}
// 分页改变时回调
const onTablePageChange2 = (page: TableDemoPageType) => {
  state.tableData2.param.pageNum = page.pageNum
  state.tableData2.param.pageSize = page.pageSize
  getTableData2()
}

const handleClick = (tab: TabsPaneContext, event: Event) => {
  // console.log(tab, event);
}

const getdetailForm = () => {
  getSpareInfoApi(id.value).then((res) => {
    if (res.code == 0) {
      detailForm.value = res.data
    }
  })
}

const inOutDialog = ref(false)
const inOutForm = ref({
  title: '',
  form: {},
  info: {}
})

const Outdetails = (row: any) => {
  inOutForm.value.title = '出库'
  inOutForm.value.form = row
  inOutForm.value.info = detailForm.value
  inOutDialog.value = !inOutDialog.value
}
const Indetails = (row: any) => {
  inOutForm.value.title = '入库'
  inOutForm.value.form = row
  inOutForm.value.info = detailForm.value
  inOutDialog.value = !inOutDialog.value
}

const closeDetail = () => {
  inOutDialog.value = !inOutDialog.value
}

let timer: any = null
const exportRecordOut = () => {
  timer && clearTimeout(timer)
  timer = setTimeout(() => {
    let params = {
      partId: id.value,
      retrievalType: state.tableData.param.retrievalType
        ? state.tableData.param.retrievalType
        : '',
      keword: state.tableData.param.keyword
        ? state.tableData.param.keyword
        : '',
      startTime: state.tableData.param.startTime
        ? state.tableData.param.retriestartTimevalType
        : '',
      endTime: state.tableData.param.endTime
        ? state.tableData.param.endTime
        : ''
    }
    if (list1.value.length == 0) {
      ElMessage.warning('暂无数据可导出')
    } else {
      singleDerivedRecordApi(params).then((res: any) => {
        let blob = new Blob([res], {
          type: 'application/vnd.ms-excel;charset=UTF-8'
        })
        let url = window.URL.createObjectURL(blob)
        const link = document.createElement('a') // 创建a标签
        link.download = '出库记录.xls'
        link.href = url
        link.click()
        URL.revokeObjectURL(url) // 释放内存
      })
    }
  }, 1000)
}

let timer2: any = null
const exportRecordIn = () => {
  timer2 && clearTimeout(timer2)
  timer2 = setTimeout(() => {
    let params = {
      partId: id.value,
      warehouseType: state.tableData2.param.warehouseType
        ? state.tableData2.param.warehouseType
        : '',
      keword: state.tableData2.param.keyword
        ? state.tableData2.param.keyword
        : '',
      startTime: state.tableData2.param.startTime
        ? state.tableData2.param.retriestartTimevalType
        : '',
      endTime: state.tableData2.param.endTime
        ? state.tableData2.param.endTime
        : ''
    }
    if (list2.value.length == 0) {
      ElMessage.warning('暂无数据可导出')
    } else {
      singleDerivedRecordInApi(params).then((res: any) => {
        let blob = new Blob([res], {
          type: 'application/vnd.ms-excel;charset=UTF-8'
        })
        let url = window.URL.createObjectURL(blob)
        const link = document.createElement('a') // 创建a标签
        link.download = '入库记录.xls'
        link.href = url
        link.click()
        URL.revokeObjectURL(url) // 释放内存
      })
    }
  }, 1000)
}

//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = {
  Indetails: Indetails,
  Outdetails: Outdetails,
  exportRecordOut: exportRecordOut,
  exportRecordIn: exportRecordIn
}
// 监听子级表格  传过来的方法
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}
</script>
<style scoped lang="scss"></style>
